package com.examsystem.service.impl;



import com.examsystem.dao.ScoreMapper;
import com.examsystem.dao.UserMapper;
import com.examsystem.pojo.vo.Result;
import com.examsystem.pojo.vo.ScoreVo;
import com.examsystem.service.ScoreService;
import com.examsystem.pojo.vo.StudentScore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

import static com.examsystem.Const.ConstMsg.*;

/**
 * @author 86134
 */
@Service("scoreService")
public class ScoreServiceImpl implements ScoreService {
    @Resource
    private ScoreMapper scoreMapper;
    @Resource
    private UserMapper userMapper;

    /*
    学生端
     */


    @Override
    public List<StudentScore> getUserScore(int userId) {
        boolean flag = userMapper.queryUserById(userId)==null;
        if (flag){
            throw new RuntimeException(CHECK_MSG_FAIL_MSG);
        }
        return scoreMapper.queryScoresByUserId(userId);
    }



    /*
    教师端
     */

    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查看成绩
     * @param choice 【1：查看单独班级的学生情况  2：参加此次考试的所有班级的average排名 】
     * @param classId 班级id
     * @param paperId 试卷id
     * @return  list集合的score对象
     */
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED, propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public List<ScoreVo> showScore(Integer choice, Integer classId, Integer paperId){
        if (choice == null || classId == null || paperId == null){
            return (List<ScoreVo>) new Result(500,"数据错误",null);
        }
//        String key = "score: "+choice+classId+paperId;
        //加上synchronized避免并发问题
        // 先从缓存获取数据如果有则直接返回
        // 如果无则查询MySQL，并将数据设置到缓存中
//        Object scoreObj = redisTemplate.boundListOps(key);
        List<ScoreVo> scoreObj = null;
        if (scoreObj == null){
            synchronized (this.getClass()){
//                scoreObj = redisTemplate.boundListOps(key);
                List<ScoreVo> scores = null;
                if (choice == NUMBER_1) {
                    //单个班级的学生成绩情况
                    scores = scoreMapper.studentScore(classId, paperId);
                }else if (choice == NUMBER_2) {
                    scores = scoreMapper.classScore(paperId);
                }
                //添加到redis中
                scoreObj=scores;
//                redisTemplate.boundListOps(key).leftPush(scores);
            }
        }
        return scoreObj;
    }
}
